package com.service.impl;

import com.common.exception.db.DeleteException;
import com.common.exception.db.InsertException;
import com.common.exception.db.UpdateException;
import com.common.paging.PagingData;
import com.dao.AdviceDao;

import com.dao.BillDao;
import com.dto.in.AddRecordDto;
import com.entity.*;
import com.service.AdvicesService;
import com.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by Administrator on 2018/10/20.
 */
@Service
public class AdviceServiceImpl implements AdvicesService {
    @Autowired
    private AdviceDao adviceDao;
    @Autowired
    private BillDao billDao;

    @Override
    public int advice(String userId, String phone, String title, String content) {
        return adviceDao.advice(userId, phone, title, content);
    }

    @Override
    @Transactional
    public synchronized int addEvaluation(Integer recordId, Integer stdUserId, Integer stdId, Integer teaUserId, Integer evaluationNum) {
        int a = adviceDao.addEvaluation(stdUserId, stdId, teaUserId, evaluationNum);
        if (a > 0) {
            int value = adviceDao.findTeacherValue(teaUserId);
            int edit = adviceDao.updateTeacherValue(teaUserId, evaluationNum);
            if (edit > 0) {
                edit = adviceDao.updateRecordAppraise(recordId);
                if (edit > 0) {
                    return edit;
                } else {
                    throw new UpdateException("修改评价状态失败");
                }
            } else {
                throw new UpdateException("修改名师值失败");
            }
        } else {
            throw new InsertException("新增失败");
        }

    }

    @Override
    public PagingData findAdvicesList(Integer page, Integer length) {
        List<AdvicesInfo> list = adviceDao.findAdvicesList(page, length);
        int count = adviceDao.findAdvicesListCount();
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public int setAdvices(Integer id) {
        return adviceDao.setAdvices(id);
    }

    @Override
    public List<Record> findReadyStatus(String stdUserId, String teaUserId, String teaId, String type, Integer limit) {
        if (stdUserId != null) {
            return adviceDao.findReadyStatusS(stdUserId, type, limit);
        } else if (teaUserId != null) {
            return adviceDao.findReadyStatusT(teaId, teaUserId, type, limit);
        } else {
            return null;
        }
    }

    @Override
    public int updateRecordStatus(Integer id) {
        return adviceDao.updateRecordStatus(id);
    }

    @Override
    public int createRecord(AddRecordDto addRecordDto) {
        addRecordDto.setRecordUUID(String.valueOf(Calendar.getInstance().getTimeInMillis()));
        int i = adviceDao.createRecord(addRecordDto);
        if (i > 0) {
            return addRecordDto.getRecordId();
        } else {
            return 0;
        }
    }

    @Override
    public int updataPayMessage(String transaction_id, String out_trade_no, String nonceStr, String payTime) {
        return adviceDao.updataPayMessage(transaction_id, out_trade_no, nonceStr, payTime);
    }

    @Override
    public int updateOrderStatus(String id, String operation) {
        if (operation.equals("2"))
            switch (adviceDao.findOrderStatus(id)) {
                case "未申请":
                    return 0;
                case "已处理":
                    return 2;
                case "新申请":
                    return 3;
                default:
                    return 4;
            }
        else
            return adviceDao.updateOrderStatus(id, operation);
    }

    @Override
    public int addRefund(Integer recordId) {
        return adviceDao.addRefund(recordId);
    }


    @Override
    public int createRecordOrder(Integer recordId, Integer fewHours, BigDecimal fewHoursPrice) {
        String fewHoursString;
        for (int i = 1; i <= fewHours; i++) {
            fewHoursString = i + "节课";
            int success = adviceDao.createRecordOrder(recordId, fewHoursString, fewHoursPrice);
            if (success <= 0) {
                return 0;
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int findRecordOrderSeveral(Integer id, Integer recordId) {
        List<RecordOrderInfo> list = adviceDao.findRecordOrder(recordId);
        Date now = new Date();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_MONTH, +7);
        Date date =calendar.getTime();
        int num = 1;
        int edit;
        for (int i = 0; i < list.size(); i++) {        //查询这个小订单是第几个
            RecordOrderInfo recordOrderInfo = list.get(i);
            if (recordOrderInfo.getId().equals(id)) {
                num = num + i;
            }
        }
        RecordOrderMoneyInfo teaUserId = adviceDao.findRecordOrderTeaUserId(id, recordId);
        if (num != 1) {         //如果不是第一个
            for (int o = 0; o < num - 1; o++) {         //如果前面有未完成的小订单  返回 -1
                RecordOrderInfo recordOrderInfo1 = list.get(o);
                if (recordOrderInfo1.getIsConfirm().equals("NO")) {
                    return -1;  // -1 为上面还有没完成的小订单
                }
            }
            edit = adviceDao.updateRecordOrderStatus(id);
            if (edit > 0) {
                if (num >= list.size()) {            //如果是最后一个小订单  需要走修改user接口
                    edit = adviceDao.updateTeaMoney(teaUserId.getTeaUserId(), teaUserId.getFewHoursPrice(),date);
                    if (edit > 0) {
                        int success = adviceDao.updateRecordStatus1(recordId);
                        if (success > 0) {
                            String uuid = UUIDUtil.get32UUID();
                            success = billDao.insertBill(teaUserId.getTeaUserId(), uuid, teaUserId.getFewHoursPrice(), 1, "课程结算");
                            if (success > 0) {
                                return 1;
                            } else {
                                throw new UpdateException("修改失败");
                            }
                        } else {
                            throw new UpdateException("修改失败");
                        }
                    } else {
                        throw new UpdateException("修改失败");
                    }
                } else {
                    edit = adviceDao.updateTeaMoney(teaUserId.getTeaUserId(), teaUserId.getFewHoursPrice(),date);
                    if (edit > 0) {
                        String uuid = UUIDUtil.get32UUID();
                        edit = billDao.insertBill(teaUserId.getTeaUserId(), uuid, teaUserId.getFewHoursPrice(), 1, "课程结算");
                        if (edit > 0) {
                            return 1;
                        } else {
                            throw new UpdateException("修改失败");
                        }
                    } else {
                        throw new UpdateException("修改失败");
                    }
                }
            } else {
                throw new UpdateException("修改失败");
            }
        } else {
            edit = adviceDao.updateRecordOrderStatus(id);
            if (edit > 0) {
                edit = adviceDao.updateTeaMoney(teaUserId.getTeaUserId(), teaUserId.getFewHoursPrice(),date);
                if (edit > 0) {
                    if (num == list.size()) {
                        int success = adviceDao.updateRecordStatus1(recordId);
                        if (success > 0) {
                            String uuid = UUIDUtil.get32UUID();
                            success = billDao.insertBill(teaUserId.getTeaUserId(), uuid, teaUserId.getFewHoursPrice(), 1, "课程结算");
                            if (success > 0) {
                                return 1;
                            } else {
                                throw new UpdateException("修改失败");
                            }
                        } else {
                            throw new UpdateException("修改失败");
                        }
                    } else {
                        String uuid = UUIDUtil.get32UUID();
                        edit = billDao.insertBill(teaUserId.getTeaUserId(), uuid, teaUserId.getFewHoursPrice(), 1, "课程结算");
                        if (edit > 0) {
                            return 1;
                        } else {
                            throw new UpdateException("修改失败");
                        }
                    }
                } else {
                    throw new UpdateException("修改失败");
                }
            } else {
                throw new UpdateException("修改失败");
            }
        }
    }

    @Override
    public List<RecordOrderInfo> findRecordOrder(Integer recordId) {
        return adviceDao.findRecordOrder(recordId);
    }

    @Override
    public int findAppliedCount(Integer stdUserId, Integer stdId) {
        return adviceDao.findAppliedCount(stdUserId, stdId);
    }

    @Override
    public int cancelOrder(Integer id) {
        return adviceDao.cancelOrder(id);
    }

    @Override
    @Transactional
    public int addMoneyRequest(String userId, String realName, BigDecimal bigDecimal, String cardId,String cPhone,String cType) {
        int success = adviceDao.addMoneyRequest(userId, realName, bigDecimal, cardId,cPhone,cType);
            if(success > 0){
                success = adviceDao.updateUserMoney(userId,bigDecimal);
                if(success > 0){
                    return success;
                }else{
                    throw new UpdateException("修改用户金额失败");
                }
            }else{
                throw new InsertException("新增提现失败");
            }
    }


    @Override
    public Record findRecordById(Integer id) {
        return adviceDao.findRecordById(id);
    }

    @Override
    @Transactional
    public int updateMoneyRequestStatus(Integer userId, String realName, BigDecimal money, String bankCardId, String uuid) {
        int i = adviceDao.updateMoneyRequestStatus(userId);
        if (i > 0) {
            //流水记账——支出
            int j = billDao.insertBill(userId, uuid, money, 2, "提现");
            if (j > 0) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    @Override
    public int updatePayStatus(Integer id, String nonceStr) {
        return adviceDao.updatePayStatus(id, nonceStr);
    }

    @Override
    public List<bill> findBill(Integer userId, String type) {
        return adviceDao.findBill(userId, type);
    }

    @Override
    public List<Price> findPrice(Integer userId) {
        return adviceDao.findPrice(userId);
    }

    @Override
    @Transactional
    public int updataSubjectPrice(Integer userId, Integer id, List<SubjectDataInfo> subjectData) {
        int count = adviceDao.findSubjectPriceNum(userId, id);
        if (count > 0) {
            int delete = adviceDao.deleteSubjectPrice(userId, id);
            if (delete > 0) {
                for (SubjectDataInfo subjectDataInfo : subjectData) {
                    int success = adviceDao.updataSubjectPrice(userId, id, subjectDataInfo.getSubjectId(), subjectDataInfo.getSubjectPrice());
                    if (success <= 0) {
                        throw new InsertException("新增失败");
                    }
                }
                return 1;
            } else {
                throw new DeleteException("删除失败");
            }
        } else {
            for (SubjectDataInfo subjectDataInfo : subjectData) {
                int success = adviceDao.updataSubjectPrice(userId, id, subjectDataInfo.getSubjectId(), subjectDataInfo.getSubjectPrice());
                if (success <= 0) {
                    throw new InsertException("新增失败");
                }
            }
            return 1;
        }
    }
}
